package com.keke.beauty.sys.login.controller;

import java.io.IOException;
import java.util.Base64;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.keke.beauty.sys.user.entity.SysUser;
import com.keke.beauty.utils.pojo.Result;
import com.keke.beauty.utils.tools.ResultUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class SysLoginController {

    /**
	 * 登录
	 */
	@PostMapping("/login")
	public Result login(String username, String password)throws IOException {
		try{
			Subject subject = SecurityUtils.getSubject();
			password = new String(Base64.getDecoder().decode(password.getBytes()));
			AuthenticationToken token = new UsernamePasswordToken(username, password);
			subject.login(token);
	        return ResultUtil.success(subject.getPrincipal());
		}catch (Exception e) {
		    log.error(e.getMessage());
			return ResultUtil.error(e.getMessage());
		}
	}

	/**
	 * 退出
	 */
	@GetMapping("logout")
	public Result logout() {
	    SecurityUtils.getSubject().logout();
	    return ResultUtil.success("退出成功");
	}
	
	/**
	 * 获取用户信息
	 * 功能描述：
	 * 创建时间：2019年2月21日 下午2:57:15
	 * @return
	 */
	@GetMapping("userinfo")
	public Result userinfo(){
	    SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
	    return ResultUtil.success(user);
	}

}
